/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.utils;

public class SequenceGenerator {
	private long value, initialValue, maxValue, minValue;
	
	public SequenceGenerator(long initialValue, long minValue, long maxValue) {
		this.value = initialValue;
		this.maxValue = maxValue;
		this.minValue = minValue;
	}
	public SequenceGenerator(long initialValue, long minValue) {
		this.value = initialValue;
		this.maxValue = Long.MAX_VALUE;
		this.minValue = minValue;
	}
	
	public SequenceGenerator(long initialValue) {
		this.value = initialValue;
		this.maxValue = Long.MAX_VALUE;
		this.minValue = Long.MIN_VALUE;
	}
	
	public long getMaxValue() {
		return this.maxValue;
	}
	
	public long getMinValue() {
		return this.minValue;
	}

	public long getInitialValue() {
		return this.initialValue;
	}
	
	public synchronized long current() {
		return this.value;
	}
	
	public synchronized long next() {
		return this.next(1);
	}
	
	public synchronized long next(long step) {
		this.value+=step;
		if(this.value > this.maxValue ) {
			this.value = this.minValue + (this.value-this.maxValue-1);
			if(this.value > this.maxValue ) {
				this.value = this.minValue;
			}
		}
		if(this.value < this.minValue ) {
			this.value = this.maxValue - (this.minValue-this.value-1);
			if(this.value < this.minValue) {
				this.value = this.maxValue;
			}
		}
		return this.value;
	}
	
	public long next(int step) {
		return this.next((long)step);
	}
	
	public long next(short step) {
		return this.next((long)step);
	}
	
	public long next(byte step) {
		return this.next((long)step);
	}	
}
